/**
 * API服务使用示例
 * 展示如何使用新的API服务层
 */

import {
  sendChatMessage,
  abortChat,
  generateAIContent,
  createContent,
  createCancellableRequest,
  processStreamResponse,
  type ChatRequest,
  type AIGenerateRequest,
  type CreateContentRequest,
} from "../services/apiService";

import { createThinkingChainRequest } from "../services/thinkingChainService";

// ==================== 示例1: 发送聊天消息 ====================
export async function exampleSendChat() {
  const chatRequest: ChatRequest = {
    question: "请帮我写一个旅行攻略",
    chatId: "test-chat-id",
    streaming: true,
  };

  try {
    const response = await sendChatMessage(chatRequest);

    // 处理流式响应
    for await (const chunk of processStreamResponse(response)) {
    }
  } catch (error) {
    console.error("聊天请求失败:", error);
  }
}

// ==================== 示例2: 带取消功能的聊天 ====================
export async function exampleCancellableChat() {
  const { signal, cancel } = createCancellableRequest();

  const chatRequest: ChatRequest = {
    question: "生成一个长篇内容",
    chatId: "test-chat-id",
    streaming: true,
  };

  try {
    // 5秒后自动取消请求
    setTimeout(() => {
      cancel();
    }, 5000);

    const response = await sendChatMessage(chatRequest, signal);

    for await (const chunk of processStreamResponse(response)) {
    }
  } catch (error) {
    if (error instanceof Error && error.name === "AbortError") {
    } else {
      console.error("请求失败:", error);
    }
  }
}

// ==================== 示例3: AI内容生成 ====================
export async function exampleAIGenerate() {
  const request: AIGenerateRequest = {
    prompt: "请分析以下内容并提取关键信息：\n这是一个关于北京旅游的攻略...",
    options: {
      temperature: 0.7,
      max_tokens: 1000,
    },
  };

  try {
    const result = await generateAIContent(request);
    return result.response;
  } catch (error) {
    console.error("AI生成失败:", error);
    throw error;
  }
}

// ==================== 示例4: 创建内容 ====================
export async function exampleCreateContent() {
  const contentData: CreateContentRequest = {
    city: "北京",
    title: "北京三日游攻略",
    pageDiv: "<div>HTML内容</div>",
    content: "# 北京三日游攻略\n\n这是一个详细的攻略...",
    durationDays: 3,
    tags: ["北京", "故宫", "天安门", "长城"],
  };

  try {
    const result = await createContent(contentData);
    return result.data?.id || result.id;
  } catch (error) {
    console.error("创建内容失败:", error);
    throw error;
  }
}

// ==================== 示例5: 思维链请求 ====================
export async function exampleThinkingChain() {
  const request = createThinkingChainRequest();

  try {
    await request.create(
      {
        question: "分析最新的AI技术趋势",
        overrideConfig: {},
        chatId: "thinking-chain-test",
        streaming: true,
      },
      {
        onSuccess: (messages) => {},
        onError: (error) => {
          console.error("思维链失败:", error);
        },
        onUpdate: (msg) => {},
      },
    );
  } catch (error) {
    console.error("思维链请求失败:", error);
  }
}

// ==================== 示例6: 人工确认请求 ====================
export async function exampleHumanInputRequest() {
  const chatRequest: ChatRequest = {
    question: "Proceed", // 固定值
    chatId: "test-chat-id",
    humanInput: {
      type: "proceed", // 或 "reject"
      startNodeId: "node-123",
      feedback: "用户确认继续",
    },
    streaming: true,
  };

  try {
    const response = await sendChatMessage(chatRequest);

    for await (const chunk of processStreamResponse(response)) {
    }
  } catch (error) {
    console.error("人工确认请求失败:", error);
  }
}

// ==================== 示例7: 错误处理 ====================
export async function exampleErrorHandling() {
  try {
    const result = await generateAIContent({
      prompt: "测试请求",
    });
    return result;
  } catch (error) {
    // 根据错误类型进行不同处理
    if (error instanceof Error) {
      if (error.message.includes("API请求失败")) {
        console.error("API服务器错误:", error);
        // 可以尝试重试或显示特定错误信息
      } else if (error.name === "AbortError") {
      } else {
        console.error("未知错误:", error);
      }
    } else {
      console.error("未知错误:", error);
    }

    throw error;
  }
}

// ==================== 示例8: 批量操作 ====================
export async function exampleBatchOperations() {
  const requests = ["生成北京攻略", "生成上海攻略", "生成广州攻略"];

  const results = await Promise.allSettled(
    requests.map(async (prompt, index) => {
      const chatRequest: ChatRequest = {
        question: prompt,
        chatId: `batch-${index}`,
        streaming: false,
      };

      return sendChatMessage(chatRequest);
    }),
  );

  results.forEach((result, index) => {
    if (result.status === "fulfilled") {
    } else {
      console.error(`请求 ${index + 1} 失败:`, result.reason);
    }
  });
}

export default {
  exampleSendChat,
  exampleCancellableChat,
  exampleAIGenerate,
  exampleCreateContent,
  exampleThinkingChain,
  exampleHumanInputRequest,
  exampleErrorHandling,
  exampleBatchOperations,
};
